package com.reapal.agent.controller;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.reapal.agent.model.AgentPayRequest;
import com.reapal.agent.model.AgentPayResponse;
import com.reapal.agent.utils.DsfFunction;
import com.reapal.agent.utils.HttpClientUtil;
import com.reapal.agent.utils.ReapalUtil;

/**
 * @author jack
 * 
 */
@Controller
@RequestMapping("test")
public class AgentPayController {

	@RequestMapping(value = "/pay", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String payBatch(Model model, AgentPayRequest payBatchRequest) {
		return "/test/pay";
	}
	@RequestMapping(value = "/payByFile", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String payBatchByFile(Model model, AgentPayRequest payBatchRequest) {
		return "/test/payByFile";
	}

	@RequestMapping(value = "/batchquery", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String payBatchQuery(Model model, AgentPayRequest payBatchRequest) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date());
		payBatchRequest.setTrans_time(date);
		return "/test/batchquery";
	}

	@RequestMapping(value = "/singlequery", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String paySingleQuery(Model model, AgentPayRequest paySingleRequest) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date());
		paySingleRequest.setTrans_time(date);
		return "test/singlequery";
	}

	@RequestMapping(value = "/balancequery", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String balanceQuery(Model model, AgentPayRequest paySingleRequest) {
		return "test/balancequery";
	}

	/**
	 * 批次提交
	 * 
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/pay_submit", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String paybatchSubmit(Model model, AgentPayRequest agentPayRequest)
			throws Exception {

		Map<String, String> map = new HashMap<String, String>(0);
		map.put("charset", ReapalUtil.getCharset());
		map.put("trans_time",
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		map.put("notify_url", ReapalUtil.getNotify_url());
		map.put("batch_no", agentPayRequest.getBatch_no());
		map.put("batch_count", agentPayRequest.getBatch_count());
		map.put("batch_amount", agentPayRequest.getBatch_amount());
		map.put("pay_type", agentPayRequest.getPay_type());
		map.put("content", agentPayRequest.getContent());
		
		String mysign = ReapalUtil.BuildMysign(map, ReapalUtil.getKey());
		
		System.out.println("签名结果==========>" + mysign);
		map.put("sign", mysign);
		map.put("sign_type", ReapalUtil.getSign_type());

		String json = JSON.toJSONString(map);

		Map<String, String> maps = ReapalUtil.addkey(json);
		maps.put("merchant_id", ReapalUtil.getMerchant_id());
		maps.put("version", ReapalUtil.getVersion());
		System.out.println("maps==========>" + com.alibaba.fastjson.JSON.toJSONString(maps));
		
		String post = HttpClientUtil.post(ReapalUtil.getUrl()
				+ "agentpay/pay", maps);
		String res = ReapalUtil.pubkey(post);
		model.addAttribute("payBatchRequest", agentPayRequest);
		model.addAttribute("msg", res);
		return "test/pay";
	}

	/**
	 * 批次查询
	 * 
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/paybatch_query", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String paybatchQuery(Model model, AgentPayRequest agentPayRequest)
			throws Exception {

		Map<String, String> map = new HashMap<String, String>(0);
		map.put("charset", ReapalUtil.getCharset());
		map.put("trans_time",
				agentPayRequest.getTrans_time().trim());
		map.put("notify_url", ReapalUtil.getNotify_url());
		map.put("batch_no", agentPayRequest.getBatch_no());
		map.put("next_tag", (agentPayRequest.getNext_tag()!=null && !"".equals(agentPayRequest.getNext_tag()))?agentPayRequest.getNext_tag():"1");       //下一页标识
		String mysign = ReapalUtil.BuildMysign(map, ReapalUtil.getKey());

		System.out.println("签名结果==========>" + mysign);
		map.put("sign", mysign);
		map.put("sign_type", ReapalUtil.getSign_type());

		String json = JSON.toJSONString(map);

		Map<String, String> maps = ReapalUtil.addkey(json);
		maps.put("merchant_id", ReapalUtil.getMerchant_id());
		maps.put("version", ReapalUtil.getVersion());
		String post = HttpClientUtil.post(ReapalUtil.getUrl()
				+ "agentpay/batchpayquery", maps);
		String res = ReapalUtil.pubkey(post);
		
		//获取下一页标识
		AgentPayResponse agentpayRsp = JSON.parseObject(res, AgentPayResponse.class);
		String nextTag = agentpayRsp.getNext_tag();
		agentPayRequest.setNext_tag(nextTag);
		model.addAttribute("payBatchRequest", agentPayRequest);
		model.addAttribute("msg", res);
		return "test/batchquery";
	}

	/**
	 * 单笔查询
	 * 
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/paysingle_query", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String paysingleQuery(Model model, AgentPayRequest agentPayRequest)
			throws Exception {

		Map<String, String> map = new HashMap<String, String>(0);
		map.put("charset", ReapalUtil.getCharset());
		map.put("trans_time",
				agentPayRequest.getTrans_time().trim());
		map.put("notify_url", ReapalUtil.getNotify_url());
		map.put("batch_no", agentPayRequest.getBatch_no());
		map.put("detail_no", agentPayRequest.getDetail_no());
		
		String mysign = ReapalUtil.BuildMysign(map, ReapalUtil.getKey());
		
		System.out.println("签名结果==========>" + mysign);
		map.put("sign", mysign);
		map.put("sign_type", ReapalUtil.getSign_type());

		String json = JSON.toJSONString(map);

		Map<String, String> maps = ReapalUtil.addkey(json);
		maps.put("merchant_id", ReapalUtil.getMerchant_id());
		maps.put("version", ReapalUtil.getVersion());
		String post = HttpClientUtil.post(ReapalUtil.getUrl()
				+ "agentpay/singlepayquery", maps);
		String res = ReapalUtil.pubkey(post);
		model.addAttribute("paySingleRequest", agentPayRequest);
		model.addAttribute("msg", res);
		return "test/singlequery";
	}

	/**
	 * 余额查询
	 *
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/balance_query", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String balance_Query(Model model, AgentPayRequest agentPayRequest)
			throws Exception {

		Map<String, String> map = new HashMap<String, String>(0);
		map.put("charset", ReapalUtil.getCharset());
		String mysign = ReapalUtil.BuildMysign(map, ReapalUtil.getKey());
		System.out.println("签名结果==========>" + mysign);
		map.put("sign", mysign);
		map.put("sign_type", ReapalUtil.getSign_type());

		String json = JSON.toJSONString(map);

		Map<String, String> maps = ReapalUtil.addkey(json);
		maps.put("merchant_id", ReapalUtil.getMerchant_id());
		maps.put("version", ReapalUtil.getVersion());
		String post = HttpClientUtil.post(ReapalUtil.getUrl()
				+ "agentpay/balancequery", maps);
		String res = ReapalUtil.pubkey(post);
		model.addAttribute("msg", res);
		return "test/balancequery";
	}
	 /**
     * 推送回调接口，融宝调用该方法返回商户结果
     * @return success：成功，其他返回均认为失败
     * @throws Exception
     */
	@RequestMapping(value = "/payback", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
    public String payback(Model model,String encryptkey, String data, HttpServletRequest request) {
        String result = null;
        System.out.println("推送回调接口encryptkey==========>" + encryptkey);
        System.out.println("推送回调接口data==========>" + data);
        try {
        	result = ReapalUtil.pubkey(encryptkey,data);
        	System.out.println("推送回调接口payback_result:"+result);
        	/*
        	 * 根据解析后的result做后续处理
        	 * */
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
	/**
	 * 通过模板 批次提交
	 * 
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/pay_submitByFile", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String paybatchSubmitByFile(MultipartFile uploadFile,Model model,HttpServletRequest request, AgentPayRequest agentPayRequest)
			throws Exception {

		 String message = "";
	        //设置响应给前台内容的PrintWriter对象
	        if (uploadFile.isEmpty()) {
	        	model.addAttribute("msg", "请选择文件后上传");
	    		return "test/payByFile";
	        }
	        final String fileName = uploadFile.getOriginalFilename();
	        String dirPath = request.getSession().getServletContext().getRealPath("/") + "upload";
	        String tarFileName = fileName.substring(0, fileName.indexOf(".") + 1) + fileName.substring(fileName.indexOf(".") + 1).toUpperCase();
	        String filePath = dirPath + File.separator + tarFileName;
	        File f = new File(filePath);
	        //文件解析格式校验
	        message = validateFile(uploadFile, dirPath, filePath);
	        if (!"".equals(message)) {
	        	
	 	       model.addAttribute("msg", message);
	 	       return "test/payByFile";
	        }
	        //解析
	        String msg="";
	        if(filePath.endsWith(".TXT")){
	        	msg = DsfFunction.readFileByLines(filePath);
	        }else if(filePath.endsWith(".XLS")){
	        	msg = DsfFunction.readExcel(filePath);
	        }else{
	        	if (f.exists()) {
	                f.delete();
	            }
	        	model.addAttribute("msg", "文件格式不对，必须是.TXT或.XLS文件");
 	    		return "test/payByFile";
	        }
	        if (msg == null || "".equals(msg)) {
	            if (f.exists()) {
	                f.delete();
	                model.addAttribute("msg", message);
	 	    		return "test/payByFile";
	            }
	        }

		
		Map<String, String> map = new HashMap<String, String>(0);
		map.put("charset", ReapalUtil.getCharset());
		map.put("trans_time",
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		map.put("notify_url", ReapalUtil.getNotify_url());
		map.put("batch_no", agentPayRequest.getBatch_no());
		map.put("batch_count", agentPayRequest.getBatch_count());
		map.put("batch_amount", agentPayRequest.getBatch_amount());
		map.put("pay_type", agentPayRequest.getPay_type());
		map.put("content", msg);
		
		String mysign = ReapalUtil.BuildMysign(map, ReapalUtil.getKey());
		
		System.out.println("签名结果==========>" + mysign);
		map.put("sign", mysign);
		map.put("sign_type", ReapalUtil.getSign_type());

		String json = JSON.toJSONString(map);

		Map<String, String> maps = ReapalUtil.addkey(json);
		maps.put("merchant_id", ReapalUtil.getMerchant_id());
		maps.put("version", ReapalUtil.getVersion());
		String post = HttpClientUtil.post(ReapalUtil.getUrl()
				+ "agentpay/pay", maps);
		String res = ReapalUtil.pubkey(post);
		model.addAttribute("payBatchRequest", agentPayRequest);
		model.addAttribute("msg", res);
		return "test/payByFile";
	}
	
	/**
	 * 验证模板批次文件格式
	 * @param uploadFile
	 * @param dirPath
	 * @param filePath
	 * @return
	 */
    public String validateFile(MultipartFile uploadFile, String dirPath, String filePath) {
        String message = "";

        final String fileName = uploadFile.getOriginalFilename();
        File targetFile = new File(dirPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //重写FilenameFilter.accept
        String[] ss = new File(dirPath).list(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                if (name.indexOf(".") != -1 && name.substring(0, name.indexOf(".")).equalsIgnoreCase(fileName.substring(0, fileName.indexOf(".")))) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        try {
            if (ss.length > 0) {
                //return "存在重名文件,请勿重复提交";
            }
            //保存
            File fileSave = new File(filePath);  //建立新文件
            uploadFile.transferTo(fileSave);     //保存文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

}
